/*
 * SpeedoDyno - Speedometer and dynamometer application for Android 
 * Copyright 2013 Guilhem VALENTIN
 * 
 * This file is part of SpeedoDyno
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with SpeedoDyno. If not, see <http://www.gnu.org/licenses/>.
 */
package com.gvalentin.speedodyno.data;

import android.location.Location;

import com.gvalentin.speedodyno.util.DoubleCapacityRollingList;

/**
 * Calculate incline by using average value.
 * - automatically remove nonsense GPS altitude values
 * - calculate average by compiling a minimum set of altitudes changes (so if altitude
 * does not change a lot, the average will be calculated against a longer travel distance)
 * 
 * Algorithm inpired from:
 * com.google.android.apps.mytracks.stats.TripStatisticsUpdater
 * http://code.google.com/p/mytracks/source/browse/MyTracks/src/com/google/android/apps/mytracks/stats/TripStatisticsUpdater.java
 * 
 * @author guilhem
 */
public class CalculatorInclineMytracks implements Calculator<Double> {

	/**
	 * The number of distance readings to smooth to get a stable signal.
	 */
	public static final int DISTANCE_SMOOTHING_FACTOR = 25;

	/**
	 * The number of elevation readings to smooth to get a somewhat accurate
	 * signal.
	 */
	public static final int ELEVATION_SMOOTHING_FACTOR = 25;

	/**
	 * The number of grade readings to smooth to get a somewhat accurate signal.
	 */
	public static final int GRADE_SMOOTHING_FACTOR = 5;


	// A buffer of the recent elevation readings (m)
	private final DoubleCapacityRollingList elevationBuffer = new DoubleCapacityRollingList(ELEVATION_SMOOTHING_FACTOR);

	// A buffer of the recent distance readings (m) for calculating grade
	private final DoubleCapacityRollingList distanceBuffer = new DoubleCapacityRollingList(DISTANCE_SMOOTHING_FACTOR);

	// A buffer of the recent grade calculations (%)
	private final DoubleCapacityRollingList gradeBuffer = new DoubleCapacityRollingList(GRADE_SMOOTHING_FACTOR);

	  
	private Double grade = 0.0d;
	
	/**
	 * Return the calculated incline
	 * @see com.gvalentin.speedodyno.data.Calculator#getData()
	 */
	@Override
	public Double getData() {
		return grade;
	}
	
	/**
	 * Calculate the incline
	 * @see com.gvalentin.speedodyno.data.Calculator#calculate(android.location.Location, android.location.Location)
	 */
	@Override
	public void update(Location previous, Location current) {
		if (current != null) {
			double elevationDifference = updateElevation(current.getAltitude());
			if (previous != null) {
			    updateGrade(previous.distanceTo(current), elevationDifference);
			}
		}
	}
	
	
    /**
	 * Updates an elevation reading.
	 *
	 * @param elevation the elevation
	 */
	private double updateElevation(double elevation) {
	    double oldAverage = elevationBuffer.getAverage();
	    elevationBuffer.add(elevation);
	    double newAverage = elevationBuffer.getAverage();
	    return elevationBuffer.isFull() ? newAverage - oldAverage : 0.0;
	}

	/**
	 * Updates a grade reading.
	 *
	 * @param distance the distance the user just traveled
	 * @param elevationDifference the elevation difference between the current
	 *          reading and the previous reading
	 */
	private void updateGrade(double distance, double elevationDifference) {
	    distanceBuffer.add(distance);
	    double smoothedDistance = distanceBuffer.getAverage();

	    /*
	     * With the error in the altitude measurement it is dangerous to divide by
	     * anything less than 5.
	     */
	    if (!elevationBuffer.isFull() || !distanceBuffer.isFull() || smoothedDistance < 5.0) {
	      return;
	    }
	    gradeBuffer.add(elevationDifference / smoothedDistance);
	    grade = gradeBuffer.getAverage();
	}
}
